/**
 * Created by sjg on 17/4/5.
 */
var CONFIG = require('../../../../common/config');
var CODE = require('../../../../common/code');
var rpcFunc=require('../../../routes/rpcSrv/rpcFunc.js');
var async = require('async');
var express = require('express');
var router = express.Router();

var ItbUserModel = require('../../../../common/mysql/mapping/ItbUserModel');
var TgDesignDocModel = require('../../../../common/mysql/mapping/TgDesignDocModel');
var TgDesignPageModel = require('../../../../common/mysql/mapping/TgDesignPageModel');
var TgUserDocModel = require('../../../../common/mysql/mapping/TgUserDocModel');
var TgUserPageModel = require('../../../../common/mysql/mapping/TgUserPageModel');
var TgUserPcModel = require('../../../../common/mysql/mapping/TgUserPcModel');

var checkUtil = require('../../util/checkUtil');
var printUtil = require('../../util/printUtil');
var tgUtil = require('../../util/tgUtil');

//------------------------------------------------------------------
/**
 * 获取模板/作品信息
 *
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数:  isDesign	是否为设计标记
 * 参数: docId	 对应文档 id, 可能是模板 id 也可能是用户文档 id, 根据 tmplFlg 区分
 * 参数: userId	用户唯一标识
 * 参数: typeL	0 未分类   1 海报  2 多页  3 ppt.  4. 印品
 *
 * 原接口: /tg/getDocInfo
 * 测试地址:  http://localhost:3000/tp/v1/document/getDocInfo
 * */
function getDocInfo(req, res, next){

    //var obj = {"designId":321,"productId":789,"coreStructure":{"version":"1","name":"会议邀请函脑图","root":{"kind":0,"obj_id":0,"value":null,"children":[{"kind":3,"obj_id":0,"value":{"min":1,"max":8,"value":"","type":11,"id":32},"children":[],"topic":"会议名称","page_index":0,"type":1,"id":"11"},{"kind":3,"obj_id":0,"value":{"value":"","type":30,"id":53,"pos":{"h":270,"an":0,"w":270,"y":0,"x":0},"mask":{"y":0,"paths":[{"h":0,"points":[[135,0,8],[210.6,0,3],[270,59.4,3],[270,135,3],[270,210.6,3],[210.6,270,3],[135,270,3],[59.4,270,3],[0,210.6,3],[0,135,3],[0,59.4,3],[59.4,0,3],[135,0,3]],"w":0}],"x":0,"w":270,"h":270}},"children":[],"topic":"会议图片","page_index":0,"type":2,"id":"12"},{"kind":1,"obj_id":0,"value":null,"children":[{"kind":2,"obj_id":0,"value":null,"children":[{"kind":3,"obj_id":0,"value":{"min":1,"max":8,"value":"","type":11,"id":32},"children":[],"topic":"名称1","page_index":0,"type":1,"id":"1311"},{"kind":3,"obj_id":0,"value":{"value":"","type":30,"id":53,"pos":{"h":270,"an":0,"w":270,"y":0,"x":0},"mask":{"y":0,"paths":[{"h":0,"points":[[135,0,8],[210.6,0,3],[270,59.4,3],[270,135,3],[270,210.6,3],[210.6,270,3],[135,270,3],[59.4,270,3],[0,210.6,3],[0,135,3],[0,59.4,3],[59.4,0,3],[135,0,3]],"w":0}],"x":0,"w":270,"h":270}},"children":[],"topic":"头像1","page_index":0,"type":2,"id":"1312"}],"topic":"嘉宾1","page_index":0,"type":1,"id":"131"},{"kind":2,"obj_id":0,"value":null,"children":[{"kind":3,"obj_id":0,"value":{"min":1,"max":8,"value":"","type":11,"id":32},"children":[],"topic":"名称2","page_index":0,"type":1,"id":"1321"},{"kind":3,"obj_id":0,"value":{"value":"","type":30,"id":53,"pos":{"h":270,"an":0,"w":270,"y":0,"x":0},"mask":{"y":0,"paths":[{"h":0,"points":[[135,0,8],[210.6,0,3],[270,59.4,3],[270,135,3],[270,210.6,3],[210.6,270,3],[135,270,3],[59.4,270,3],[0,210.6,3],[0,135,3],[0,59.4,3],[59.4,0,3],[135,0,3]],"w":0}],"x":0,"w":270,"h":270}},"children":[],"topic":"头像2","page_index":0,"type":2,"id":"1322"}],"topic":"嘉宾2","page_index":0,"type":1,"id":"132"}],"topic":"邀请嘉宾","page_index":0,"type":1,"id":"13"}],"topic":"会议邀请函","page_index":0,"type":1,"id":"1"}}};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = req.body.device || req.query.device;
    var userId = Number(req.body.userId || req.query.userId || 0);
    var docId = Number(req.body.docId || req.query.docId || 0);
    var isDesign = Number(req.body.isDesign || req.query.isDesign || 0);
    var typeL = req.body.typeL || req.query.typeL;

    // check parameter
    if (typeof docId=='undefined' || isNaN(docId) || docId==null || docId==0) {
        return tgUtil.ret_func_json(0,"文档id为空",{},res);
    }
    if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        return tgUtil.ret_func_json(0,'用户id为空',{},res);
    }

    var entity = null;
    if(isDesign) {
        entity = new TgDesignDocModel({
            design_id: docId,
            del_flg: 0
        });
    } else {
        entity = new TgUserDocModel({
            doc_id: docId,
            del_flg: 0
        });
    }
    entity.findFromDB(function(err,items) {
        if (err) {
            console.log('document.js [getDocInfo] Find Err: ' + err);
            return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }
        if(items && items.length>0) {
            // 替换非法字符
            var strFtData = items[0].data
                .replace(/\n/g,'\\n').replace(/\t/g,'').replace(/\r/g,'') //.replace(/\\"/g,'\\\\\\"')
                .replace(/[\x00-\x09\x0B-\x1F\x7F-\x9F]/g, "");
            var retData = {
                designId: items[0].design_id,
                designNm: items[0].design_name||'',
                productId: items[0].doc_id||0,
                productNm: items[0].doc_name||'',
                coreStructure: JSON.parse(strFtData||'{}')
            };

            return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);

        } else {
            return tgUtil.ret_func_json(0,'未找到数据',{},res);
        }
    });
}
router.get('/getDocInfo', getDocInfo);
router.post('/getDocInfo', getDocInfo);

//------------------------------------------------------------------
/**
 * 保存用户文档
 * 参数: device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: userId	用户唯一标识
 * 参数: doc	对应文档 json 字符串
 * 参数[可选]: clrHis	是否删除切换模版历史记录(等于1时删除,默认不删除)
 * 参数: typeL	0 未分类   1 海报  2 多页  3 ppt, 4 印品
 *
 * 原接口: /tg/saveUserDocOnly
 * 测试地址: http://localhost:3000/tp/v1/document/saveUserDocOnly
 * */
function saveUserDocOnly(req, res, next) {

    //var obj = {"designId":234,"productId":12345};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = req.body.device || req.query.device;
    var docStr = req.body.doc || req.query.doc;
    var doc = JSON.parse(docStr);
    var userId = Number(req.body.userId || req.query.userId || 0);
    var clrHis = Number(req.body.clrHis || req.query.clrHis || "0");
    var skipUserChk = Number(req.body.skipUserChk || req.query.skipUserChk || "0");
    var typeL = req.body.typeL || req.query.typeL;
    if(CONFIG.DEBUG==1) clrHis = 0;

    // check parameter
    if((typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0)) {
        return tgUtil.ret_func_json(0,CODE.USER_ID_EMPTY,{},res);
    }
    if(typeof doc=='undefined' || doc == null){
        return tgUtil.ret_func_json(0,CODE.DOC_DATA_EMPTY,{},res);
    } else {
        if(doc.designId=='undefined' || doc.designId==null) {
            return tgUtil.ret_func_json(0,'设计模版ID为空',{},res);
        }
    }

    // proc
    async.parallel({
        getDesign: function(callback){
            // 检索design
            var entityD = new TgDesignDocModel({
                design_id: doc.designId,
                del_flg: 0
            });
            entityD.findFromDB(function(err, items) {
                if (err) {
                    console.log('document.js [saveUserDocOnly] Check design_id Err: ' + err);
                    return callback(err, null);
                }

                if (items != null && items.length > 0) {
                    return callback(null, items[0]);

                } else {
                    console.log('document.js [saveUserDocOnly] design_id invalid ');
                    return callback("无效DESIGN_ID", null);
                }
            });
        },

        getUser: function(callback){
            if(skipUserChk == 1){
                // 直接返回
                return callback(null, {user_id: userId, user_type:1});
            } else {
                // 检索user
                var entity = new ItbUserModel({
                    //uuid    : uuid,
                    user_id : userId,
                    del_flg : 0
                });
                entity.findFromDB(function(err, items){
                    if (err){
                        console.log('document.js [saveUserDocOnly] Check user_id Err: '+err);
                        return callback(error, null);
                    }

                    if (items != null && items.length > 0) {
                        return callback(null, items[0]);

                    } else {
                        console.log('document.js [saveUserDocOnly] user_id invalid ');
                        return callback(CODE.USER_ID_INVAILD, null);
                    }
                });
            }
        }

    }, function(error, result){
        if (error) {
            return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        var userItem = result.getUser;
        var designItem = result.getDesign;

        if (doc.productId=='undefined' || doc.productId==null || Number(doc.productId)==0) {
            // 新规
            var newDocEntity = new TgUserDocModel({
                tg_id: designItem.tg_id,
                map_id: designItem.map_id,
                design_id: designItem.design_id,
                doc_name: doc.productNm || '我的作品',// doc.coreStructure.name
                user_id: userItem.user_id,
                user_type: userItem.user_type,
                purpose: 0,
                size_id: designItem.size_id,
                type_id: designItem.type_id,
                data: JSON.stringify(doc.coreStructure) || '',
                hash_tag: JSON.stringify(doc.tag) || '[]',// TODO
                ver: doc.coreStructure.version || 0,
                update_by: userItem.user_id,
            });
            // insert document
            newDocEntity.saveToDB(function(err, newDocId){
                if (err) {
                    console.log('document.js [saveUserDocOnly] Ins Doc Err: '+err);
                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                var retData = {
                    designId: designItem.design_id,
                    productId: newDocId,
                };

                return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
            });

        } else {
            // 更新doc
            var updDocEnt = new TgUserDocModel({
                doc_id: doc.productId,// Key
                doc_name: doc.productNm || '我的作品',// doc.coreStructure.name
                data: JSON.stringify(doc.coreStructure) || '',
                hash_tag: JSON.stringify(doc.tag) || '[]',// TODO
                ver: doc.coreStructure.version || 0,
                update_by: userItem.user_id,
            });
            updDocEnt.updateToDB(function(err){
                if (err) {
                    console.log('document.js [saveUserDocOnly(upd)] Upd Doc Err: '+err);
                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                // 逻辑删除page
                var delPgEnt = new TgUserPageModel({
                    doc_id: doc.productId,
                    update_by: userItem.user_id,
                });
                delPgEnt.delPageLogic(function(delErr){
                    if (delErr) {
                        console.log('document.js [saveUserDocOnly(upd)] Del Pages Err: ' + delErr);
                        return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                    }

                    // 逻辑删除pc
                    var delPcEnt = new TgUserPcModel({
                        doc_id: doc.productId,
                        update_by: userItem.user_id,
                    });
                    delPcEnt.delPcLogic(function(delErr2){
                        if (delErr2) {
                            console.log('document.js [saveUserDocOnly(upd)] Del PCs Err: ' + delErr2);
                            return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                        }

                        // 返回值
                        var retData = {
                            designId: designItem.design_id,
                            productId: doc.productId,
                        };

                        if(1==clrHis){
                            // 清除切换历史
                            doClrHis(doc.productId, function(clrErr, clrRet){
                                if (clrErr) {
                                    console.log('document.js [saveUserDocOnly(upd)] doClrHis Err: '+clrErr);
                                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                                }

                                return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
                            });

                        } else {
                            return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
                        }
                    });
                });

            });
        }
    });

    // 删除切换模版记录
    function doClrHis(docId,callback){
        var url = CONFIG.SWITCH_SERVER_DOMAIN +':'+CONFIG.SWITCH_SERVER_PORT+'/tgSwitch/clrSwitchHis?'
            +'docId='+docId;

        superagent.get(url)
            .end(function(err, res){
                if(err){
                    console.log('document.js [saveUserDocOnly] SuperAgent clrSwitchHis Err: ' + err);
                    return callback(err, null);
                }

                var retJson = JSON.parse(res.text);
                if(retJson.success){
                    return callback(null,retJson.data);

                } else {
                    return callback(retJson.msg, null);
                }
            }
        );
    }
}
router.get('/saveUserDocOnly', saveUserDocOnly);
router.post('/saveUserDocOnly', saveUserDocOnly);

//------------------------------------------------------------------
/**
 * 获取模板/作品文档预览
 *
 * 参数:  device	"0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 *
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网"
 * 参数: isDesign	是否为模板文档
 * 参数: docId	 对应文档 id, 可能是设计 id 也可能是作品 id, 根据 isDesign 区分
 * 参数: userId	 用户唯一标识
 * 参数: his	 是否获取历史记录
 * 参数: typeL	0 未分类   1 海报  2 多页  3 ppt. 4 印品
 *
 * 原接口: /tg/getDocPreviewEx
 * 测试地址: http://localhost:3000/tp/v1/document/getDocPreviewEx
 * */
function getDocPreviewEx(req, res, next) {
    //var obj = {"designId":787,"productNm":"双十一促销","designer":{"id":756,"avatarUrl":"http://oss-image-xx.png"},"preview":[{"pageId":989,"thumb":"http://oss-sdklhf.jpg"}],"switchLimit":5,"history":[{"designId":908,"thumb":"http://oss-sdlkjfh.jpg"},{"designId":909,"thumb":"http://oss-sdlkjfh.jpg"}]};
    //return printUtil.ret_func_json(1, '成功', obj, res);

    var device = req.body.device || req.query.device;
    var docId = Number(req.body.docId || req.query.docId || '0');
    var isDesign = Number(req.body.isDesign || req.query.isDesign || '0');
    var userId = Number(req.body.userId || req.query.userId || '0');
    var getHis = Number(req.body.his || req.query.his || '0');
    if(CONFIG.DEBUG==1) getHis=0;
    var typeL = Number(req.body.typeL || req.query.typeL || '0'); // 对于印品需要去除出血线

    if (typeof docId=='undefined' || isNaN(docId) || docId==null || docId==0) {
        return tgUtil.ret_func_json(0,'用户文档id为空',{},res);
    }
    //if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
    //    return tgUtil.ret_func_json(0,'无效用户id',{},res);
    //}


    // 获取文档
    var docEntity = null;
    if(isDesign) {
        docEntity = new TgDesignDocModel({
            design_id: docId,
            del_flg: 0
        });
    } else {
        docEntity = new TgUserDocModel({
            doc_id: docId,
            del_flg: 0,
            withoutPgInfo: 1// 新文档没有pg
        });
    }
    docEntity.getDocInfoById(function (findErr, docs) {
        if (findErr) {
            console.log('document.js [getDocPreviewEx] find doc Err: ' + findErr);
            return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
        }

        if(docs && docs.length>0){
            var itemInfo = docs[0];

            // 获取preview
            var pgEntity = null;
            if(isDesign) {
                pgEntity = new TgDesignPageModel({
                    design_id: docId,
                    del_flg:0
                });
            }else{
                pgEntity = new TgUserPageModel({
                    doc_id: docId,
                    del_flg:0
                });
            }
            pgEntity.getPageInfoById(function(error, items){
                if(error){
                    console.log('document.js [getDocPreviewEx] getPageInfoById Err: '+error);
                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                }

                // process success
                var pageData = [];
                var doTypeset = false;
                if (items != null && items.length > 0) {
                    for (var i in items){
                        var item = items[i];

                        // 只要有未生成预览图的页面就返回error
                        if (item.thumb == null || item.thumb.trim().length == 0) {
                            doTypeset = true;
                            break;
                        }

                        // 组合page数据
                        var pageItem = {
                            pageId: item.page_id,
                            index: item.page_index,
                            thumb: item.thumb||''
                        };
                        pageData.push(pageItem);
                    }
                } else {
                    if(!isDesign) {// 新建用户文档无page,pc
                        doTypeset = true;
                    }
                }

                // 返回值
                var retData={
                    docId: docId,
                    preview: pageData,
                    price: Number(itemInfo.min_tmpl_price|| '0')
                };
                // todo 客服电话
                retData.service = '17762500830';

                if (doTypeset) {
                    // 重新排版
                    rpcFunc.typesetTGDoc(docId,function (ret) {
                        // 再次获取
                        pgEntity.getPageInfoById(function (error2, items2) {
                            if (error2) {
                                console.log('document.js [getDocPreviewEx] Re-getPageInfoById Err: ' + error2);
                                return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                            }

                            // process success
                            pageData = [];
                            if (items2 != null && items2.length > 0) {
                                for (var n in items2) {
                                    var item = items2[n];

                                    // 只要有未生成预览图的页面就返回error
                                    if (item.thumb == null || item.thumb.trim().length == 0) {
                                        return tgUtil.ret_func_json(0,CODE.PAGE_THUMB_EMPTY,{},res);
                                    }

                                    // 组合page数据
                                    var pageItem = {
                                        pageId: item.page_id,
                                        index: item.page_index,
                                        thumb: item.thumb||''
                                    };
                                    pageData.push(pageItem);
                                }
                            }

                            // 更新预览
                            retData.preview = pageData;

                            if(isDesign){
                                // 设计文档名
                                retData.docNm = itemInfo.design_name||'';
                            } else {
                                // 当前用户文档所使用的设计模版id
                                retData.designId = itemInfo.design_id;
                                // 用户文档名
                                retData.docNm = itemInfo.doc_name||'';
                            }

                            // 获取切换历史
                            tgUtil.getSwitchHis(getHis, docId,userId, function(err, retHis){
                                if (err) {
                                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                                }
                                retData.history = retHis || [];

                                // 删除印品预览图的出血
                                tgUtil.adjust_size_of_image (typeL, docId, isDesign, retData.preview,function(err2,size){
                                    if(err2){
                                        return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                                    }
                                    retData.size = size; // 返回size
                                    return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
                                });

                            });

                        });
                    });
                } else {
                    // 无需排版
                    if(isDesign){
                        // 设计文档名
                        retData.docNm = itemInfo.design_name||'';
                    } else {
                        // 当前用户文档所使用的设计模版id
                        retData.designId = itemInfo.design_id;
                        // 用户文档名
                        retData.docNm = itemInfo.doc_name||'';
                    }

                    // 获取设计师信息
                    tgUtil.getUserInfo(itemInfo.user_id, function(error, userInfo){
                        if(userInfo){
                            retData.designer = {
                                "id":userInfo.user_id,
                                "avatarUrl":userInfo.head_url
                            };
                        }

                        // 获取切换历史
                        tgUtil.getSwitchHis(getHis, docId,userId, function(err, retHis){
                            if (err) {
                                return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                            }
                            retData.history = retHis || [];

                            // 获取 印品的出血
                            tgUtil.adjust_size_of_image (typeL, docId, isDesign, retData.preview,function(err2,size){
                                if(err2){
                                    return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
                                }
                                retData.size = size; // 返回size
                                return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,retData,res);
                            });
                        });

                    });

                }
            });

        } else {
            return tgUtil.ret_func_json(0,"未检索到文档",{},res);
        }
    });
}
router.get('/getDocPreviewEx', getDocPreviewEx);
router.post('/getDocPreviewEx', getDocPreviewEx);

//------------------------------------------------------------------
/**
 * 根据模板创建用户作品
 *
 * 参数: device
 * 0 表示从pc来的请求
 * 1 标识一键生成iOS端
 * 2 标识一键生成android端
 * 3  标识一键生成 app 嵌入网页
 * 4 标识一键生成 web 端
 * 5 标识一键生成微信端
 * 101 表示pc美化大师/102表示pc wps/103表示wps android/104表示wps ios
 * 201 标识利楚商务
 * 301 标识酒单网
 *
 * 参数: userId  用户唯一标识
 * 参数: id      模板的唯一标识
 *
 * 返回值: {"success":1,"msg":"成功","data":{"designId":989,"productId":10001}}
 * */
function copyDesignToUser(req, res, next){

    var device = req.body.device || req.query.device;
    var userId = Number(req.body.userId || req.query.userId || '0');
    var designId = Number(req.body.id || req.query.id || '0');

    // check parameter
    if (typeof designId=='undefined' || isNaN(designId) || designId==null || designId==0) {
        return tgUtil.ret_func_json(0,"无效模版id",{},res);
    }
    if (typeof userId=='undefined' || isNaN(userId) || userId==null || userId==0) {
        return tgUtil.ret_func_json(0,'无效用户id',{},res);
    }

    printUtil.copyDesignToUserDoc(userId, designId, function(err, newDocId){
        if(Number(newDocId||'0')>0) {
            return tgUtil.ret_func_json(1,CODE.OPERATION_SUCCESS,{designId:designId, productId:newDocId},res);
        }

        return tgUtil.ret_func_json(0,CODE.OPERATION_FAILED,{},res);
    });
}
router.get('/copyDesignToUser', copyDesignToUser);
router.post('/copyDesignToUser', copyDesignToUser);

//------------------------------------------------------------------
module.exports = router;